'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');
const ModelName = 'User'
class UserService extends Service {
    /**
     * 根据分页和搜索条件获取
     */
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            attributes: { exclude: ['password'] },
            where: {
                ...where,
            },
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
    }
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
        });
    }
    /**
     * 注册用户数据
     * @param {Object} data
     */
    async register(data) {
        if (!data.phone) {
            throw new Error('请输入手机号');
        }
        if (!data.password) {
            throw new Error('请输入密码');
        }
        const userExists = await this.ctx.model[ModelName].findOne({
            attributes: ['id'],
            where: {
                phone: data.phone,
            },
        });
        if (userExists) throw new Error('该手机号已经存在');
        const newUser = await this.ctx.model[ModelName].create(data);
        return newUser.dataValues;
    }

    /**
     * 根据条件查询用户信息
     * @param {Object} user
     */
    async login({ password, phone }) {
        // 根据邮箱查询用户是否存在
        let user = await this.ctx.model[ModelName].findOne({
            where: { phone },
        });
        if (!user) {
            throw new Error('请先注册');
        }
        // 校验密码
        const isMatch = user.password === password;
        if (!isMatch) {
            throw new Error('密码不正确');
        }
        user = user.dataValues;
        return user;
    }

    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
    }

    /**
     * 根据id删除对应的用户
     * @param {Number} uid
     */
    async deleteUserById(id) {
        // 删除成功在删除用户
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }

    /**
     * 根据ID修改用户信息
     * @param {Number} id 用户ID
     * @param {Object} data 要修改的用户信息
     */
    async update(id, data) {
        const { username } = data;
        const andWhere = { id: { [Op.ne]: id } };
        let neenCheck = false;
        if (username) {
            neenCheck = true;
            andWhere.username = username;
        }

        if (neenCheck) {
            const userExists = await this.ctx.model[ModelName].findOne({
                attributes: ['id'],
                where: { [Op.and]: andWhere },
            });
            if (userExists) throw new Error('该账号已注册');
        }

        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }
    /**
     * 更新用户密码
     * @param {Number} id 用户ID
     * @param {Object} data 新密码和旧密码
     */
    async updatePassword(id, data) {
        const user = await this.ctx.model[ModelName].findByPk(id);
        if (!user) {
            throw new Error('该账号不存在');
        }

        // 旧密码是否有误, 正确就直接修改
        const isValid = bcrypt.compareSync(data.old_password, user.password);
        if (!isValid) {
            throw new Error('旧密码输入不正确');
        }
        user.password = data.new_password;
        return await user.save();
    }

    async wxH5login(data) {
        const { code } = data;
        try {
            const { access_token, openid} = await this.getWxH5OpenId(code)
            const userInfo = await this.getWxH5UserInfo(access_token, openid)
            return await this.loginFormWxH5(userInfo)
        } catch (error) {
            console.log('error',error)
            throw new Error('登录失败');
        }
    }
    async getWxH5OpenId(code) {
        const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wxH5config.appid}&secret=${wxH5config.secret}&code=${code}&grant_type=authorization_code`;
        const response = await this.ctx.curl(url, { dataType: 'json' });
        console.log(response)
        if (response.status === 200) {
            if (response.data.errcode) {
                throw new Error(response.data.errmsg);
            } else {
                /**
                 *  access_token: '83_vhk2_5FyIg97ShefJqezlqQCD4AWeK7xToK2FzN-hbafuRBe_n6I3sTJvYLqfXtzwxowrdC6pAvPoovRpE6FWo1N2iRqeHkFocWX8E7PUwE',
                 *     expires_in: 7200,
                 *     refresh_token: '83_J7zVVBAdPr57dswqn4Dz4Z9QPPw_IGKEyIICuEkLgsc21TtnmBGTQhos8iheGoZePmIvuQfobJhbnmvZbjdp64m9-hHQODIGZRIeQUGYF5I',
                 *     openid: 'oG5mi6YItlS1bcV96H96nM6B0QIs',
                 *     scope: 'snsapi_userinfo'
                 */
                return {
                    openid: response.data.openid,
                    access_token: response.data.access_token,
                }
            }
        } else {
            throw new Error('登录失败');
        }
    }
    async getWxH5UserInfo(access_token, openid) {
        const url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
        const response = await this.ctx.curl(url, { dataType: 'json' });
        console.log(response)
        if (response.status === 200) {
            if (response.data.errcode) {
                throw new Error(response.data.errmsg);
            } else {
                return response.data
            }
        } else {
            throw new Error('登录失败');
        }
    }
    async loginFormWxH5(userInfo) {
        console.log(userInfo)
        const {
            openid,
            nickname,
            sex,
            headimgurl,
            unionid
        } = userInfo;
        const { User } = this.ctx.model;
        // 根据手机号查询用户是否存在
        let user = await User.findOne({
            where: {
                wx_openid: openid,
            },
        });
        if (!user) {
            // 去注册
            let createUser = await User.create({
                wx_openid: openid,
                nickname: nickname,
                avatar_url: headimgurl,
            })
            let userValue = createUser.dataValues;
            delete userValue.password;
            console.log('userValue',userValue)
            return userValue;
        } else {
            // // 判断密码是否有误
            // const isValid = user.password === password
            // if (!isValid) {
            //     throw new Error('密码错误');
            // }
            return user.dataValues
        }
    }

}

module.exports = UserService;
